/**
 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.cmc.service.merchant.service.impl;

import java.util.Date;

import com.cmc.service.merchant.DeleteMerchantHasAgentsException;
import com.cmc.service.merchant.MerchantEntryDuplicateCodeException;
import com.cmc.service.merchant.MerchantEntryNotEnoughRequiredFieldsException;
import com.cmc.service.merchant.NoSuchMerchantEntryException;
import com.cmc.service.merchant.model.MerchantEntry;
import com.cmc.service.merchant.service.base.MerchantEntryLocalServiceBaseImpl;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.OrganizationConstants;
import com.liferay.portal.service.ServiceContext;

/**
 * The implementation of the merchant entry local service.
 * 
 * <p>
 * All custom service methods should be put in this class. Whenever methods are
 * added, rerun ServiceBuilder to copy their definitions into the
 * {@link com.cmc.service.merchant.service.MerchantEntryLocalService} interface.
 * 
 * <p>
 * This is a local service. Methods of this service will not have security
 * checks based on the propagated JAAS credentials because this service can only
 * be accessed from within the same VM.
 * </p>
 * 
 * @author ntcuong1
 * @see com.cmc.service.merchant.service.base.MerchantEntryLocalServiceBaseImpl
 * @see com.cmc.service.merchant.service.MerchantEntryLocalServiceUtil
 */
public class MerchantEntryLocalServiceImpl extends
		MerchantEntryLocalServiceBaseImpl {
	/*
	 * NOTE FOR DEVELOPERS:
	 * 
	 * Never reference this interface directly. Always use {@link
	 * com.cmc.service.merchant.service.MerchantEntryLocalServiceUtil} to access
	 * the merchant entry local service.
	 */

	public MerchantEntry addMerchant(long userId,MerchantEntry merchantEntry,
			ServiceContext serviceContext) throws PortalException,
			SystemException {
		// validate information of merchant
		validateFields(merchantEntry);

		// check code unique
		try {
			MerchantEntry m = merchantEntryPersistence.findByCode(merchantEntry
					.getCode());
			if (m != null)
				throw new MerchantEntryDuplicateCodeException();
		} catch (SystemException ex) {
			throw ex;
		} catch (NoSuchMerchantEntryException ex) {
			// valid
		}

		if (merchantEntry.isOrganization()) {

			long parentOrganizationId = OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;

			if (Validator.isNotNull(merchantEntry.getParentId())) {
				try {
					MerchantEntry parent = merchantEntryPersistence
							.findByPrimaryKey(merchantEntry.getParentId());
					if (parent != null
							&& Validator.isNotNull(parent.getOrganizationId())) {
						parentOrganizationId = parent.getOrganizationId();
					}
				} catch (NoSuchMerchantEntryException ex) {
					// Valid
				} catch (SystemException ex) {
					throw ex;
				}
			}
			
			Organization organization = organizationLocalService.addOrganization(
					userId, 
					parentOrganizationId,
					merchantEntry.getTitle(),
					merchantEntry.getOrganizationType(),
					merchantEntry.isRecursable(), 
					merchantEntry.getRegionId(),
					merchantEntry.getCountryId(),
					merchantEntry.getOrganizationStatus(),
					merchantEntry.getDescription(),
					merchantEntry.isSites(),
					serviceContext);
			
			merchantEntry.setOrganizationId(organization.getOrganizationId());
		}
		
		Date currentDate = new Date();

		MerchantEntry merchant = merchantEntryPersistence
				.create(counterLocalService.increment(MerchantEntry.class
						.getName()));

		merchant.setCompanyId(merchantEntry.getCompanyId());
		merchant.setCreateDate(currentDate);
		merchant.setModifiedDate(currentDate);
		merchant.setCreatorUserId(userId);
		
		merchant.setType(merchantEntry.getType());
		merchant.setCode(merchantEntry.getCode());
		merchant.setTitle(merchantEntry.getTitle());
		merchant.setSites(merchantEntry.getSites());
		merchant.setDescription(merchantEntry.getDescription());
		merchant.setLongitude(merchantEntry.getLongitude());
		merchant.setLatitude(merchantEntry.getLatitude());
		merchant.setParentId(merchantEntry.getParentId());
		merchant.setOrganizationId(merchantEntry.getOrganizationId());
		merchant.setOrganization(merchantEntry.isOrganization());
		merchant.setOrganizationStatus(merchantEntry.getOrganizationStatus());
		merchant.setOrganizationType(merchantEntry.getOrganizationType());
		merchant.setRecursable(merchantEntry.isRecursable());
		merchant.setSites(merchantEntry.isSites());
		merchant.setParentId(merchantEntry.getParentId());		

		merchantEntryPersistence.update(merchant, false);

		return merchant;
	}
	
	public void deleteMerchant(long merchantId) throws SystemException, PortalException {
		MerchantEntry merchant = merchantEntryPersistence.findByPrimaryKey(merchantId);
		
		
		if (merchantEntryPersistence.containsAgentEntries(merchantId)) {
			throw new DeleteMerchantHasAgentsException();
		}
		
		if (merchant.isOrganization()) {			
			long organizationId = merchant.getOrganizationId();
			organizationLocalService.deleteOrganization(organizationId);
		}
		
		merchantEntryPersistence.remove(merchantId);
	}

	private void validateFields(MerchantEntry merchant) throws PortalException {
		if (Validator.isNull(merchant.getCompanyId())) 
			throw new MerchantEntryNotEnoughRequiredFieldsException("companyId");
		
		if (Validator.isNull(merchant.getTitle())) 
			throw new MerchantEntryNotEnoughRequiredFieldsException("title");
		
		if (Validator.isNull(merchant.getCode()))
			throw new MerchantEntryNotEnoughRequiredFieldsException("code");
	}
}